// pages/userInfoCenter/index.js

const App = getApp();
const { Dialog, Toast } = require("../../../config/modal")
const utils = require("../../../utils/util")
const { LOCATION } = require("../../../config/login.js")

Page({
    /**
     * 页面的初始数据
     */
    data: {
        theamTextColor: App.globalData.theamTextColor,
        capsuleBarHeight: App.$getMenuButtonHeight(),
        file: {
            maxSize: 5242880,
            maxCount: 3,
            list: []
        },
        form: {
            id: '',
            content: "",
            wechatId: "",
            images: '',
            sex: 1,
            schoolName: '',
        },
        showLoacation: false,
        locations: {
            prefix: '',
            regeocode: {},
            list: []
        },
        rules:
        {
            content: {
                msg: "您的交友简介(介绍自己)",
                required: true,
            },
            wechatId: { val: "", msg: "请填写微信", required: true },
            schoolName: { val: "", msg: "请选择学校", required: true },
        },
        config: null,
    },
    URL: {
        save: "/tuodan/push",
        config: "/tuodan/config",
        toPay: "/tuodan/toPayPush",
    },
    page: {
        schoolPage: "/pages/school/index",
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        this.setData({
            'form.sex': utils.isInvalid(options.sex) ? 1 : options.sex
        })
        if (App.$isAuth()) {
            let user = App.$getUserInfo();
            if (!utils.isInvalid(user.schoolName)) {
                this.setData({
                    'form.schoolName': user.schoolName,
                    'form.wechatId': user.wechatId
                })
            }
        }
    },
    onShow() {
        App.$get(true, this.URL.config, {}, res => {
            if (res.R) {
                this.setData({
                    config: res.data
                })
            }
        })
    },

    /**
 * 点击抽取，拉取支付
 */
    toGetUser(callback) {
        let _this = this;
        App.$post(true, this.URL.toPay, {}, res => {
            if (res.R) {
                wx.requestPayment
                    (
                        {
                            "timeStamp": res.data.timeStamp,
                            "nonceStr": res.data.nonceStr,
                            "package": res.data.packageStr,
                            "signType": res.data.signType,
                            "paySign": res.data.paySign,
                            "success": function (res) {
                                console.log("吊起支付成功");
                                callback(res)
                            },
                            "fail": function (res) { console.log("吊起支付失败") },
                            "complete": function (res) { }
                        }
                    )
                return;
            }

        })
    },


    onChangeFormField(e) {
        let key = 'form.' + utils.getEvent(e).name
        this.setData({
            [key]: e.detail.value == undefined ? e.detail : e.detail.value,
        })
    },


    onContentChange(e) {
        this.setData({
            'form.content': e.detail.value
        })
    },

    // 获取当前所在位置
    toSelectSchoolName() {
        App.$navigateTo(this.page.schoolPage, false)
    },
    onSchoolNameChange(e) {
        this.setData({
            'form.schoolName': e.detail,
        })
    },




    // 关闭弹框
    closeLocation() {
        this.setData({
            'showLoacation': false,
        })
    },

    // 提交地址信息
    submitInfo() {

        // 处理图片 转base64

        let imgs = this.data.file.list
        let imgBase64 = "";
        imgs.forEach(file => {
            imgBase64 += utils.fileToBase64Sync(file.url) + "&&";
        })
        // console.log(imgBase64);
        this.setData({
            'form.images': imgBase64
        })

        if (utils.isInvalid(this.data.form.content)) {
            Toast('需要输入自我介绍哦 😊～')
            return;
        }

        if (utils.isInvalid(this.data.form.wechatId)) {
            Toast('需要填写联系方式哦 😊～')
            return;
        }

        if (utils.isInvalid(this.data.form.schoolName)) {
            Toast('请填写学校哦 😊～')
            return;
        }

        this.save();
    },

    save() {
        let _this = this;
        if (this.data.config.pushStart) {
            this.toGetUser(res => {
                wx.showLoading({
                    title: '加载中',
                    mask: true,
                })
                App.$post(true, _this.URL.save, _this.data.form, res => {
                    _this.reqResult(res);
                })
            })
            return;
        }
        App.$post(true, _this.URL.save, _this.data.form, res => {
            _this.reqResult(res);
        })
    }
    ,
    reqResult(res) {
        wx.showLoading({
            title: '加载中',
            mask: true,
        })
        if (res.R) {
            Dialog.alert({
                message: res.msg,
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "确定",
            }).then(() => {
                // this.goBack();
                App.$redirectTo('/pages/tuodan/index', false);
            })
        }
    }
    ,

    // 文件读取前
    fileBefore(event) {
        event.detail.callback(true)
    }

    , fileOversize(event) {
        Dialog.alert({
            message: '图片每张只允许5M以内的照片',
            width: "250px",
            confirmButtonColor: "#D2691E",
            confirmButtonText: "关闭",
        }).then(() => {
        });
    },

    fileDelete(event) {
        let index = event.detail.index;
        let files = this.data.file.list;
        files.splice(index, 1);
        this.setData({
            "file.list": files,
        })
    }

    // 证件选择
    , afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        const files = event.detail.file;
        let sourceFiles = this.data.file.list;
        files.forEach(file => {
            sourceFiles.push({ url: file.url, name: "" })
        })
        this.setData({
            "file.list": sourceFiles
        })
    }

    , goBack() {
        wx.navigateBack();
    }

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    , onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
